package com.lzh.main.controller;

import com.lzh.main.pojo.dto.Result;
import com.lzh.main.service.UserAccountService;
import com.lzh.main.utils.AliyunOSSOperator;
import com.lzh.main.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/user/account/")
public class UserAccountController {
    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @PostMapping("register/")
    public Result register(@RequestBody Map<String, String> data){
        String username = data.get("username");
        String password = data.get("password");
        String confirmPassword = data.get("confirmPassword");
        String email = data.get("email");
        return userAccountService.register(username, password, confirmPassword, email);
    }

    @PostMapping("login/")
    public Result login(@RequestBody Map<String, String> data) {
        String account = data.get("account"); // 使用统一的account参数
        String password = data.get("password");

        // 检查参数
        if (account == null || account.isEmpty()) {
            return Result.error("请提供账号");
        }

        return userAccountService.login(account, password);
    }

    @GetMapping("info/")
    public Result getInfo() {
        return userAccountService.getUserInfo();
    }

    @PostMapping("upload/")
    public Result uploadAvatar(MultipartFile file) {
        // 检查上传文件是否为空
        if (!file.isEmpty()) {
            // 获取原始文件名用于后续处理
            String originalFilename = file.getOriginalFilename();
            // 提取文件扩展名（如 .jpg/.png）
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成唯一文件名（UUID去横杠 + 扩展名）
            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;

            // 从安全上下文获取当前认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            // 获取用户详细信息（自定义实现类）
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            // 提取用户ID用于更新操作
            Integer userId = userDetails.getUser().getId();

            try {
                // 调用阿里云OSS服务上传文件字节流，返回文件访问URL
                String url = aliyunOSSOperator.upload(file.getBytes(), uniqueFileName);
                // 更新用户头像URL到数据库
                return userAccountService.updateUserPhoto(userId, url);
            } catch (Exception e) {
                // 统一异常处理，抛出运行时异常
                throw new RuntimeException("文件上传失败", e);
            }
        }
        // 文件为空时返回错误信息
        return Result.error("上传失败：文件不能为空");
    }

    @PostMapping("update-username/")
    public Result updateUsername(@RequestBody Map<String, String> data) {
        String newUsername = data.get("newUsername");

        if (newUsername == null || newUsername.trim().isEmpty()) {
            return Result.error("请提供新的用户名");
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        Integer userId = userDetails.getUser().getId();

        return userAccountService.updateUsername(userId, newUsername);
    }
}
